package cn.sinata.wanglin.village.activity;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.xilada.xldutils.activitys.ImagePagerActivity;
import com.xilada.xldutils.activitys.TitleActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.aliyunoss.OssBean;
import cn.sinata.wanglin.aliyunoss.UpLoadImageUtils;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;

/**
 * 举报页面
 */
public class ReportActivity extends TitleActivity {
    @BindView(R.id.rg_report)
    RadioGroup rg_report;//
    @BindView(R.id.rv_upphoto)
    RecyclerView rv_upphoto;//所有的相册
    BaseRecyclerAdapter allphotoAdapter;
    private ArrayList<String> mImageinfos=new ArrayList<>();
    private  final int MAX_NUMBER=4;
    private String friendId=null;
    private String userid=null;
    @Override
    protected int setContentId() {
        return R.layout.activity_report;
    }
    @Override
    protected void initView() {
        super.initView();
        setTitle("举报");
        friendId=getIntent().getStringExtra("friendId");
        userid= SharedPreferencesUtils.getString(Constant.SP_USERID);
        addRightButton("提交", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                commitContent();
            }
        });
        if(allphotoAdapter==null){
            mImageinfos.add("-1");
            GridLayoutManager mgr = new GridLayoutManager(mContext, 4);
            rv_upphoto.setLayoutManager(mgr);
            allphotoAdapter= new BaseRecyclerAdapter<String>(mImageinfos, R.layout.item_myimage_grid) {
                @Override
                public void onBind(final int position, final String data, ViewHolder holder) {
                    if("-1".equals(data)){
                        ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(Uri.parse("res://mipmap/"+R.mipmap.ic_addimage));
                        holder.bind(R.id.iv_deletemyimg).setVisibility(View.GONE);
                        holder.bind(R.id.image).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                selectImages();
                            }
                        });
                    }else {
                        ((SimpleDraweeView) holder.bind(R.id.image)).setImageURI(Uri.parse("file://" + data));
                        holder.bind(R.id.iv_deletemyimg).setVisibility(View.VISIBLE);
                        holder.bind(R.id.image).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                int current=position;
                                ArrayList<String> showPhoto=new ArrayList<String>();
                                for(int i=0;i<mImageinfos.size();i++){
                                    if(!"-1".equals(mImageinfos.get(i))){
                                        showPhoto.add(mImageinfos.get(i));
                                    }else{
                                        current--;
                                    }

                                }
                                ActivityUtil.create(mContext).go(ImagePagerActivity.class)
                                        .put(ImagePagerActivity.URLS, showPhoto)
                                        .put(ImagePagerActivity.CURRENT_POSITION, current)
                                        .start();
                            }
                        });
                        holder.bind(R.id.iv_deletemyimg).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if(mImageinfos.size()==9&&!"-1".equals(mImageinfos.get(0))){
                                    mImageinfos.remove(position);
                                    mImageinfos.add(0,"-1");
                                }else{
                                    mImageinfos.remove(position);
                                }
                                allphotoAdapter.notifyDataSetChanged();
                            }
                        });
                    }
                }
            };
            rv_upphoto.setAdapter(allphotoAdapter);
        }
    }

    private void commitContent() {
        RadioButton mRadioButton= (RadioButton) findViewById(rg_report.getCheckedRadioButtonId());
        String reportContent= mRadioButton.getText().toString();
        if(mImageinfos.size()!=1){
            //有图片先上传图片。
            ArrayList<String> showPhoto=new ArrayList<String>();
            for(int i=0;i<mImageinfos.size();i++){
                if(!"-1".equals(mImageinfos.get(i))){
                    showPhoto.add(mImageinfos.get(i));
                }
            }
            upImagesToOss(reportContent,showPhoto);
        }else{
            showDialog();
            report(reportContent,null);
        }
    }
    private void report(String content, String url) {
        HttpManager.report(userid,friendId,content,url).subscribe(new ResultDataSubscriber<JsonObject>(this) {
            @Override
            public void onSuccess(String msg, JsonObject jsonObject) {
                showToast(msg);
                setResult(1);
                finish();
            }
        });
    }
    private void selectImages(){
        int maxnumber= MAX_NUMBER-mImageinfos.size()+1;
        ActivityUtil.create(mContext).go(MultiImageSelectorActivity.class)
                .put(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true)
                .put(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxnumber)
                .put(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI)
                .startForResult(3);


    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==RESULT_OK){
            if(requestCode==3&&data!=null){
                int maxnumber= MAX_NUMBER-mImageinfos.size()+1;
                ArrayList<String> resultList = new ArrayList<String>();
                resultList=data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if(maxnumber==resultList.size()){
                    mImageinfos.remove(0);
                }
                mImageinfos.addAll(resultList);
                allphotoAdapter.notifyDataSetChanged();
            }
        }
    }
    private void upImagesToOss(final String content , ArrayList<String> resultList){

        final ArrayList<OssBean>  mOssBeans=new ArrayList<>();
        for (int i=0;i<resultList.size();i++){
            Utils.systemErr("-path-->"+resultList.get(i));
            mOssBeans.add(new OssBean(resultList.get(i)));
        }

        Observable<List<OssBean>> mObservable= new UpLoadImageUtils(mOssBeans).uploadimg();
        mObservable.doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showDialog("上传中...");
            }
        })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<OssBean>>() {
                    @Override
                    public void onCompleted() {
                        dismissDialog();
                    }
                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onNext(List<OssBean> ossBeen) {
                        if(ossBeen!=null&&ossBeen.size()!=0){
                            JSONArray mJSONArray=new JSONArray();
                            for (int i=0;i<ossBeen.size();i++){
                                Utils.systemErr("-getUrlkey-->"+ossBeen.get(i).getUrlkey());
                                try {
                                    JSONObject mJSONObject=new JSONObject();
                                    mJSONObject.put("img",ossBeen.get(i).getUrlkey());
                                    mJSONObject.put("scale","1.0");
                                    mJSONArray.put(mJSONObject);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            Utils.systemErr("-imgUrl-->"+mJSONArray.toString());
                            report(content,mJSONArray.toString());
                        }
                    }
                });


    }
}
